package com.meixiang.adapter.myFundAdapter;

import android.app.Activity;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lzy.okhttputils.request.BaseRequest;
import com.meixiang.R;
import com.meixiang.dialog.LoadingDialog;
import com.meixiang.dialog.TradersPasswordtKeyDialog;
import com.meixiang.entity.fund.FundTradeRecodeBean;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.recyclerview.RecyclerAdapter;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbStrUtil;

import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 交易记录
 * author:xyj
 */
public class DealRecordAdapter extends RecyclerAdapter<DealRecordAdapter.ViewHolder> {
    private Context mContext;
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_NORMAL = 1;
    private View mHeaderView; //頭部
    private int mHeadCount = 1; //头部视图的个数
    private List<FundTradeRecodeBean> mRecodeBean;
    private Activity activity;
    private TradersPasswordtKeyDialog dialog ;
    private LoadingDialog loadingDialog;

    public DealRecordAdapter(Context context, Activity activity) {
        this.mContext = context;
        this.activity = activity;
        loadingDialog = new LoadingDialog(context);
    }

    public void refreshData(List<FundTradeRecodeBean> mRecodeBean) {
        this.mRecodeBean = mRecodeBean;
        notifyDataSetChanged();
    }

    public void setHeaderView(View headerView) {
        mHeaderView = headerView;
        notifyItemInserted(0);
    }

    public View getHeaderView() {
        return mHeaderView;
    }

    /**
     * 判断当前Item的类型
     *
     * @param position
     * @return
     */
    @Override
    public int getItemViewType(int position) {
        if (mHeaderView == null) return TYPE_NORMAL;
        if (position == 0) return TYPE_HEADER;
        return TYPE_NORMAL;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mHeaderView != null && viewType == TYPE_HEADER) {
            return new ViewHolder(mHeaderView);
        }
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_fund_detial_deal_record_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        if (getItemViewType(position) == TYPE_HEADER) return;
        final int pos = getRealPosition(holder);
        FundTradeRecodeBean recodeBean = mRecodeBean.get(pos);
        holder.tv_trade_type.setText(mRecodeBean.get(pos).getTrade_type());
        if("0".equals(recodeBean.getColor())){ //0红1绿2灰
            holder.tv_fund_status.setTextColor(ContextCompat.getColor(mContext, R.color.fund_money_color));

        }if("1".equals(recodeBean.getColor())){
            holder.tv_fund_status.setTextColor(ContextCompat.getColor(mContext, R.color.fund_confirm_color));
        }if("2".equals(recodeBean.getColor())){
            holder.tv_fund_status.setTextColor(ContextCompat.getColor(mContext, R.color.black_9));
        }
        holder.tv_fund_status.setText(recodeBean.getFund_status());
        holder.tv_created_at.setText(recodeBean.getCreated_at());
        if("卖出".equals(recodeBean.getTrade_type())){ //卖出的份额
            holder.tv_confirm_amount.setText(recodeBean.getApply_amount());
        }else{
            holder.tv_confirm_amount.setText(AbStrUtil.ChangeF3D(recodeBean.getApply_amount())+"元");
        }
        holder.tv_confirm_date.setText(recodeBean.getConfirm_date());
        if(!"".equals(recodeBean.getConfirm_amount())){
            holder.tv_confirm_money.setText("确认金额：" + AbStrUtil.ChangeF3D(recodeBean.getConfirm_amount()));
        }
        if(!"".equals(recodeBean.getNav())){
            holder.tv_confirm_nev.setText("确认净值：" + recodeBean.getNav());
        }
        if(!"".equals(recodeBean.getConfirm_share())){
            holder.tv_confirm_quotient.setText("确认份额：" + recodeBean.getConfirm_share());
        }
        if(!"".equals(recodeBean.getFee())){
            holder.tv_poundage.setText("手续费：" + AbStrUtil.ChangeF3D(recodeBean.getFee()));
        }
        if ("0".equals(recodeBean.getIs_cancel())) { //表示可撤单
            holder.fund_detial_deal_parent_layout.setEnabled(true);
            holder.fund_detial_deal_parent_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog = new TradersPasswordtKeyDialog(activity, "交易密码", "", new TradersPasswordtKeyDialog.OnCustomDialogListener() {

                        @Override
                        public void getPayPassWord(TradersPasswordtKeyDialog paymentKeyDialog, String password) {
                            //撤单
                            IsCancalHttp(password,pos);
                        }
                    });
                }
            });
        }else{
            holder.fund_detial_deal_parent_layout.setEnabled(false);
        }
        if("0".equals(recodeBean.getCanceled())){ //这个字段标识撤单之后是否可以展开 0 可以展开 1 不可以展开
            holder.ll_fund_detial_show_more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (holder.ll_more.getVisibility() == View.GONE) {
                        holder.ll_more.setVisibility(View.VISIBLE);
                        holder.iv_show_more.setBackgroundResource(R.mipmap.ic_suit_up);
                    } else {
                        holder.ll_more.setVisibility(View.GONE);
                        holder.iv_show_more.setBackgroundResource(R.mipmap.ic_suit_down);
                    }
                }
            });
        }
    }

    /**
     * 得到真實的position
     *
     * @param holder
     * @return
     */
    public int getRealPosition(RecyclerView.ViewHolder holder) {
        int position = holder.getLayoutPosition();
        return mHeaderView == null ? position : position - 1;
    }

    @Override
    public int getItemCount() {
        return mRecodeBean == null ? mHeadCount : mRecodeBean.size() + mHeadCount;
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.iv_fund_detial_show_more)
        ImageView iv_show_more;
        @Bind(R.id.ll_fund_detial_show_more)
        LinearLayout ll_fund_detial_show_more ;
        @Bind(R.id.fund_detial_ll_more)
        LinearLayout ll_more;
        @Bind(R.id.tv_trade_type)
        TextView tv_trade_type;
        @Bind(R.id.tv_created_at)
        TextView tv_created_at;
        @Bind(R.id.tv_confirm_amount)
        TextView tv_confirm_amount;
        @Bind(R.id.tv_fund_status)
        TextView tv_fund_status;
        @Bind(R.id.tv_confirm_date)
        TextView tv_confirm_date; //确认日期
        @Bind(R.id.tv_confirm_money)
        TextView tv_confirm_money; //确认金额
        @Bind(R.id.tv_confirm_nev)
        TextView tv_confirm_nev; // 确认净值
        @Bind(R.id.tv_confirm_quotient)
        TextView tv_confirm_quotient; //确认份额
        @Bind(R.id.tv_poundage)
        TextView tv_poundage; //手续费
        @Bind(R.id.fund_detial_deal_parent_layout)
        LinearLayout fund_detial_deal_parent_layout;

        ViewHolder(View view) {
            super(view);
            if (view == mHeaderView) return;
            ButterKnife.bind(this, view);
        }
    }

    /**
     * 撤单网络请求
     */
    private void IsCancalHttp(String password,final int position) {
        String url = Config.FUND_ORDER_CANCEL + "?trade_id=" + mRecodeBean.get(position).getId() + "&trade_pwd=" + password;
        HttpUtils.getC(url,new HttpCallBack(activity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(mContext,message);
            }

            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                if (loadingDialog != null && !loadingDialog.isShowing())
                    loadingDialog.show();
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                if (loadingDialog != null && loadingDialog.isShowing())
                    loadingDialog.dismiss();
                dialog.dismiss();
            }

            @Override
            public void onResponse(boolean isFromCache, JSONObject jsonObject, Request request, Response response) {
                super.onResponse(isFromCache, jsonObject, request, response);
                if(jsonObject.optInt("code") == 0){
                    Tool.showTextToast(mContext,jsonObject.optJSONObject("data").optString("err_msg"));
                }else{
                    if(jsonObject.has("data")){
                        Tool.showTextToast(mContext,jsonObject.optJSONObject("data").optString("err_msg"));
                    }else{
                        Tool.showTextToast(mContext,jsonObject.optString("err_msg"));
                    }
                }
            }
        });
    }

}
